import 'package:flutter/material.dart';
import 'package:intl/intl.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: '高级计数器',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(
          seedColor: Colors.deepPurple,
          brightness: Brightness.light,
        ),
        useMaterial3: true,
      ),
      darkTheme: ThemeData.dark().copyWith(
        colorScheme: ColorScheme.fromSeed(
          seedColor: Colors.deepPurple,
          brightness: Brightness.dark,
        ),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: '高级计数器'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> with SingleTickerProviderStateMixin {
  int _counter = 0;
  int _maxCount = 100;
  int _minCount = 0;
  int _step = 1;
  bool _darkMode = false;
  final List<int> _history = [];
  late AnimationController _animationController;
  final PageController _pageController = PageController();
  int _currentPage = 0;
  final List<Color> _themeColors = [
    Colors.deepPurple,
    Colors.blue,
    Colors.green,
    Colors.orange,
    Colors.pink,
  ];
  Color _selectedColor = Colors.deepPurple;

  @override
  void initState() {
    super.initState();
    _animationController = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 500),
    );
  }

  void _incrementCounter() {
    setState(() {
      if (_counter + _step <= _maxCount) {
        _counter += _step;
        _history.add(_counter);
        _animationController.forward(from: 0);
      } else {
        _showSnackBar('已达到最大值: $_maxCount');
      }
    });
  }

  void _decrementCounter() {
    setState(() {
      if (_counter - _step >= _minCount) {
        _counter -= _step;
        _history.add(_counter);
        _animationController.forward(from: 0);
      } else {
        _showSnackBar('已达到最小值: $_minCount');
      }
    });
  }

  void _showSnackBar(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        duration: const Duration(seconds: 1),
      ),
    );
  }

  void _resetCounter() {
    setState(() {
      _counter = 0;
      _history.add(0);
      _animationController.forward(from: 0);
    });
  }

  void _setStep(int step) {
    setState(() {
      _step = step;
    });
  }

  void _setLimits() {
    showDialog(
      context: context,
      builder: (context) {
        int min = _minCount;
        int max = _maxCount;
        return AlertDialog(
          title: const Text('设置计数器范围'),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              TextField(
                keyboardType: TextInputType.number,
                decoration: const InputDecoration(
                  labelText: '最小值',
                  border: OutlineInputBorder(),
                ),
                onChanged: (value) => min = int.tryParse(value) ?? min,
              ),
              const SizedBox(height: 16),
              TextField(
                keyboardType: TextInputType.number,
                decoration: const InputDecoration(
                  labelText: '最大值',
                  border: OutlineInputBorder(),
                ),
                onChanged: (value) => max = int.tryParse(value) ?? max,
              ),
            ],
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.pop(context),
              child: const Text('取消'),
            ),
            ElevatedButton(
              onPressed: () {
                if (min < max) {
                  setState(() {
                    _minCount = min;
                    _maxCount = max;
                  });
                  Navigator.pop(context);
                } else {
                  _showSnackBar('最小值必须小于最大值');
                }
              },
              child: const Text('保存'),
            ),
          ],
        );
      },
    );
  }

  void _showHistory() {
    showModalBottomSheet(
      context: context,
      builder: (context) {
        return Container(
          padding: const EdgeInsets.all(16),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              const Text(
                '计数历史',
                style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
              ),
              const SizedBox(height: 16),
              Expanded(
                child: _history.isEmpty
                    ? const Center(child: Text('暂无历史记录'))
                    : ListView.builder(
                  itemCount: _history.length,
                  itemBuilder: (context, index) {
                    final reversedIndex = _history.length - index - 1;
                    return ListTile(
                      leading: CircleAvatar(
                        backgroundColor: _selectedColor.withOpacity(0.2),
                        child: Text('${index + 1}'),
                      ),
                      title: Text(
                        '计数: ${_history[reversedIndex]}',
                        style: TextStyle(
                          color: _selectedColor,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      subtitle: Text(
                        DateFormat('yyyy-MM-dd HH:mm:ss').format(
                          DateTime.now().subtract(
                            Duration(minutes: reversedIndex),
                          ),
                        ),
                      ),
                      trailing: IconButton(
                        icon: const Icon(Icons.delete),
                        onPressed: () {
                          setState(() {
                            _history.removeAt(reversedIndex);
                          });
                        },
                      ),
                    );
                  },
                ),
              ),
              Align(
                alignment: Alignment.centerRight,
                child: TextButton(
                  onPressed: () {
                    setState(() {
                      _history.clear();
                    });
                    Navigator.pop(context);
                  },
                  child: const Text('清空历史'),
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  void _toggleDarkMode() {
    setState(() {
      _darkMode = !_darkMode;
    });
  }

  void _changeThemeColor(Color color) {
    setState(() {
      _selectedColor = color;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Theme(
      data: _darkMode ? ThemeData.dark() : Theme.of(context),
      child: Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
          centerTitle: true,
          actions: [
            IconButton(
              icon: Icon(_darkMode ? Icons.light_mode : Icons.dark_mode),
              onPressed: _toggleDarkMode,
            ),
          ],
        ),
        body: PageView(
          controller: _pageController,
          onPageChanged: (index) => setState(() => _currentPage = index),
          children: [
            _buildCounterScreen(),
            _buildStatisticsScreen(),
            _buildThemesScreen(),
          ],
        ),
        bottomNavigationBar: BottomNavigationBar(
          currentIndex: _currentPage,
          onTap: (index) {
            setState(() => _currentPage = index);
            _pageController.animateToPage(
              index,
              duration: const Duration(milliseconds: 300),
              curve: Curves.easeInOut,
            );
          },
          items: const [
            BottomNavigationBarItem(
              icon: Icon(Icons.calculate),
              label: '计数器',
            ),
            BottomNavigationBarItem(
              icon: Icon(Icons.bar_chart),
              label: '统计',
            ),
            BottomNavigationBarItem(
              icon: Icon(Icons.palette),
              label: '主题',
            ),
          ],
        ),
        floatingActionButton: Column(
          mainAxisAlignment: MainAxisAlignment.end,
          children: [
            FloatingActionButton(
              heroTag: 'increment',
              onPressed: _incrementCounter,
              tooltip: '增加',
              backgroundColor: _selectedColor,
              child: const Icon(Icons.add),
            ),
            const SizedBox(height: 16),
            FloatingActionButton(
              heroTag: 'decrement',
              onPressed: _decrementCounter,
              tooltip: '减少',
              backgroundColor: _selectedColor.withOpacity(0.7),
              child: const Icon(Icons.remove),
            ),
            const SizedBox(height: 16),
            FloatingActionButton(
              heroTag: 'reset',
              onPressed: _resetCounter,
              tooltip: '重置',
              backgroundColor: Colors.grey,
              child: const Icon(Icons.refresh),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildCounterScreen() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          ScaleTransition(
            scale: Tween(begin: 1.0, end: 1.2).animate(
              CurvedAnimation(
                parent: _animationController,
                curve: Curves.elasticOut,
              ),
            ),
            child: Container(
              padding: const EdgeInsets.all(24),
              decoration: BoxDecoration(
                color: _selectedColor.withOpacity(0.1),
                borderRadius: BorderRadius.circular(20),
                border: Border.all(
                  color: _selectedColor,
                  width: 2,
                ),
              ),
              child: Text(
                '$_counter',
                style: TextStyle(
                  fontSize: 80,
                  fontWeight: FontWeight.bold,
                  color: _selectedColor,
                ),
              ),
            ),
          ),
          const SizedBox(height: 40),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              _buildStepButton(1),
              _buildStepButton(5),
              _buildStepButton(10),
            ],
          ),
          const SizedBox(height: 20),
          Text(
            '当前步长: $_step',
            style: const TextStyle(fontSize: 18),
          ),
          const SizedBox(height: 10),
          Text(
            '范围: $_minCount - $_maxCount',
            style: const TextStyle(fontSize: 16, color: Colors.grey),
          ),
          const SizedBox(height: 30),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              ElevatedButton.icon(
                icon: const Icon(Icons.history),
                label: const Text('历史记录'),
                onPressed: _showHistory,
                style: ElevatedButton.styleFrom(
                  backgroundColor: _selectedColor.withOpacity(0.2),
                  foregroundColor: _selectedColor,
                ),
              ),
              const SizedBox(width: 20),
              ElevatedButton.icon(
                icon: const Icon(Icons.light),
                label: const Text('设置范围'),
                onPressed: _setLimits,
                style: ElevatedButton.styleFrom(
                  backgroundColor: _selectedColor.withOpacity(0.2),
                  foregroundColor: _selectedColor,
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildStepButton(int step) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 8.0),
      child: ChoiceChip(
        label: Text('+$step'),
        selected: _step == step,
        onSelected: (selected) => _setStep(step),
        selectedColor: _selectedColor,
        labelStyle: TextStyle(
          color: _step == step ? Colors.white : null,
        ),
      ),
    );
  }

  Widget _buildStatisticsScreen() {
    return Padding(
      padding: const EdgeInsets.all(16.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text(
            '统计信息',
            style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
          ),
          const SizedBox(height: 20),
          Card(
            child: Padding(
              padding: const EdgeInsets.all(16.0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  const Text(
                    '计数统计',
                    style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                  ),
                  const SizedBox(height: 16),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      _buildStatCard('当前计数', '$_counter'),
                      _buildStatCard('历史记录', '${_history.length}'),
                    ],
                  ),
                  const SizedBox(height: 16),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      _buildStatCard('最小值', '$_minCount'),
                      _buildStatCard('最大值', '$_maxCount'),
                    ],
                  ),
                ],
              ),
            ),
          ),
          const SizedBox(height: 20),
          Card(
            child: Padding(
              padding: const EdgeInsets.all(16.0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  const Text(
                    '最近操作',
                    style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                  ),
                  const SizedBox(height: 16),
                  if (_history.isEmpty)
                    const Center(child: Text('暂无操作历史'))
                  else
                    SizedBox(
                      height: 150,
                      child: ListView.builder(
                        itemCount: _history.length > 5 ? 5 : _history.length,
                        itemBuilder: (context, index) {
                          final reversedIndex = _history.length - index - 1;
                          return ListTile(
                            leading: CircleAvatar(
                              backgroundColor: _selectedColor.withOpacity(0.2),
                              child: Text('${index + 1}'),
                            ),
                            title: Text('计数: ${_history[reversedIndex]}'),
                            subtitle: Text(
                              DateFormat('MM-dd HH:mm').format(
                                DateTime.now().subtract(
                                  Duration(minutes: reversedIndex),
                                ),
                              ),
                            ),
                          );
                        },
                      ),
                    ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildStatCard(String title, String value) {
    return Expanded(
      child: Card(
        color: _selectedColor.withOpacity(0.1),
        child: Padding(
          padding: const EdgeInsets.all(12.0),
          child: Column(
            children: [
              Text(
                title,
                style: TextStyle(
                  fontSize: 16,
                  color: _selectedColor,
                ),
              ),
              const SizedBox(height: 8),
              Text(
                value,
                style: const TextStyle(
                  fontSize: 24,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildThemesScreen() {
    return Padding(
      padding: const EdgeInsets.all(16.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text(
            '主题设置',
            style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
          ),
          const SizedBox(height: 20),
          Card(
            child: Padding(
              padding: const EdgeInsets.all(16.0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  const Text(
                    '主题颜色',
                    style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                  ),
                  const SizedBox(height: 16),
                  Wrap(
                    spacing: 12,
                    runSpacing: 12,
                    children: _themeColors
                        .map((color) => _buildColorChoice(color))
                        .toList(),
                  ),
                ],
              ),
            ),
          ),
          const SizedBox(height: 20),
          Card(
            child: Padding(
              padding: const EdgeInsets.all(16.0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  const Text(
                    '其他设置',
                    style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                  ),
                  const SizedBox(height: 16),
                  SwitchListTile(
                    title: const Text('深色模式'),
                    value: _darkMode,
                    onChanged: (value) => setState(() => _darkMode = value),
                    secondary: const Icon(Icons.dark_mode),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildColorChoice(Color color) {
    return ChoiceChip(
      label: Container(
        width: 24,
        height: 24,
        color: color,
      ),
      selected: _selectedColor == color,
      onSelected: (selected) => _changeThemeColor(color),
      selectedColor: color.withOpacity(0.3),
    );
  }

  @override
  void dispose() {
    _animationController.dispose();
    _pageController.dispose();
    super.dispose();
  }
}